package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.outlined.ThumbUp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 楼中楼版本的评论组件
 */
@Composable
fun NestedCommentItem(
    comment: Comment,
    onReplyClick: (Comment) -> Unit = {},
    onDeleteClick: (Long) -> Unit = {},
    onRefreshComments: () -> Unit = {}
) {
    var isLiked by remember { mutableStateOf(comment.isLiked) }
    var likeCount by remember { mutableStateOf(comment.likeCount) }
    var showReplyInput by remember { mutableStateOf(false) }
    var showReplies by remember { mutableStateOf(false) }
    var replies by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoadingReplies by remember { mutableStateOf(false) }
    
    val currentUser = UserState.currentUser
    val isCurrentUser = currentUser?.id == comment.userId
    val communityApiService = remember { CommunityApiService() }
    val scope = rememberCoroutineScope()
    
    // 加载回复
    LaunchedEffect(comment.id, showReplies) {
        if (showReplies && replies.isEmpty() && !isLoadingReplies) {
            isLoadingReplies = true
            try {
                val result = communityApiService.getReplies(comment.id, 1, 10)
                result.onSuccess { data ->
                    val replyList = data["replies"] as? List<Map<String, Any>> ?: emptyList()
                    replies = replyList.map { replyData ->
                        Comment(
                            id = (replyData["id"] as? Number)?.toLong() ?: 0L,
                            postId = (replyData["postId"] as? Number)?.toLong() ?: 0L,
                            userId = (replyData["userId"] as? Number)?.toLong() ?: 0L,
                            content = replyData["content"] as? String ?: "",
                            likeCount = (replyData["likeCount"] as? Number)?.toInt() ?: 0,
                            isLiked = replyData["isLiked"] as? Boolean ?: false,
                            createdAt = replyData["createdAt"] as? String ?: "",
                            author = replyData["author"] as? String,
                            parentId = (replyData["parentId"] as? Number)?.toLong(),
                            rootId = (replyData["rootId"] as? Number)?.toLong(),
                            isDeleted = replyData["isDeleted"] as? Boolean ?: false
                        )
                    }
                }
            } catch (e: Exception) {
                // 处理错误
            } finally {
                isLoadingReplies = false
            }
        }
    }

    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(8.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp)
            ) {
                // 用户头像和用户名
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 头像占位符
                    Box(
                        modifier = Modifier
                            .size(32.dp)
                            .clip(CircleShape)
                            .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.1f)),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = (comment.author?.firstOrNull() ?: "?").toString(),
                            color = MaterialTheme.colorScheme.primary,
                            fontWeight = FontWeight.Bold,
                            fontSize = 14.sp
                        )
                    }
                    
                    Spacer(modifier = Modifier.width(8.dp))
                    
                    Column {
                        Text(
                            text = comment.author ?: "匿名用户",
                            fontWeight = FontWeight.Medium,
                            fontSize = 14.sp,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        Text(
                            text = comment.createdAt,
                            fontSize = 12.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 评论内容
                if (comment.isDeleted) {
                    Text(
                        text = "该评论已被删除",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        style = MaterialTheme.typography.bodyMedium.copy(
                            fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                        )
                    )
                } else {
                    Text(
                        text = comment.content,
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurface,
                        lineHeight = 20.sp
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 操作按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 点赞按钮
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.clickable {
                            // 切换点赞状态
                            isLiked = !isLiked
                            likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                            
                            // TODO: 实现点赞API调用
                        }
                    ) {
                        Icon(
                            imageVector = if (isLiked) Icons.Filled.ThumbUp else Icons.Outlined.ThumbUp,
                            contentDescription = "点赞",
                            tint = if (isLiked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = likeCount.toString(),
                            fontSize = 12.sp,
                            color = if (isLiked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                    
                    // 回复按钮
                    TextButton(
                        onClick = { 
                            showReplyInput = !showReplyInput
                            onReplyClick(comment)
                        },
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Text("回复", fontSize = 12.sp)
                    }
                    
                    // 删除按钮（仅当前用户可见）
                    if (isCurrentUser) {
                        TextButton(
                            onClick = { onDeleteClick(comment.id) },
                            colors = ButtonDefaults.textButtonColors(
                                contentColor = MaterialTheme.colorScheme.error
                            )
                        ) {
                            Text("删除", fontSize = 12.sp)
                        }
                    }
                }
            }
        }
        
        // 回复输入框
        if (showReplyInput) {
            NestedReplyInput(
                parentComment = comment,
                onSendReply = { replyContent ->
                    scope.launch {
                        try {
                            val result = communityApiService.createReply(
                                postId = comment.postId,
                                parentId = comment.id,
                                rootId = comment.rootId ?: comment.id,
                                content = replyContent
                            )
                            result.onSuccess {
                                showReplyInput = false
                                onRefreshComments()
                            }.onFailure {
                                // TODO: 显示错误消息
                            }
                        } catch (e: Exception) {
                            // TODO: 显示错误消息
                        }
                    }
                },
                onCancel = {
                    showReplyInput = false
                }
            )
        }
        
        // 楼中楼展开/收起
        if (replies.isNotEmpty() || isLoadingReplies) {
            NestedCommentToggle(
                isExpanded = showReplies,
                replyCount = replies.size,
                onToggle = { showReplies = !showReplies }
            )
        }
        
        // 显示子回复
        if (showReplies) {
            if (isLoadingReplies) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        strokeWidth = 2.dp
                    )
                }
            } else if (replies.isNotEmpty()) {
                replies.forEach { reply ->
                    NestedCommentItem(
                        comment = reply,
                        onReplyClick = { replyComment ->
                            onReplyClick(replyComment)
                        },
                        onDeleteClick = { replyId ->
                            onDeleteClick(replyId)
                        },
                        onRefreshComments = onRefreshComments
                    )
                }
            }
        }
    }
}

/**
 * 楼中楼展开/收起组件
 */
@Composable
fun NestedCommentToggle(
    isExpanded: Boolean,
    replyCount: Int,
    onToggle: () -> Unit,
    modifier: Modifier = Modifier
) {
    if (replyCount > 0) {
        Card(
            modifier = modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp, vertical = 2.dp)
                .clickable { onToggle() },
            elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
            )
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = if (isExpanded) "收起回复" else "查看 $replyCount 条回复",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.primary,
                    fontWeight = MaterialTheme.typography.bodySmall.fontWeight
                )
            }
        }
    }
}